import React, { useRef, useState, useEffect } from 'react';
import { Card, Form, Input, Select, Button, Upload, message, Row, Col } from 'antd';
import { SettingOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { Option } = Select;

const OneKeyBackground: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');
  const [tourVisible, setTourVisible] = useState(false);
  
  // 使用HTML元素的ref引用方式
  const styleRef = useRef<HTMLDivElement>(null);
  const colorRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const uploadRef = useRef<HTMLDivElement>(null);
  const submitRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  
  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };
  
  const handleSubmit = (values: any) => {
    setLoading(true);
    
    // 模拟图片生成过程
    setTimeout(() => {
      // 这里应该是调用AI生成图片的API
      // 现在使用占位图模拟
      setImageUrl('https://via.placeholder.com/800x600?text=AI+Generated+Background');
      message.success('背景图片生成成功！');
      setLoading(false);
    }, 2000);
  };
  
  // 上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    accept: 'image/*',
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('请上传图片文件！');
      }
      return isImage;
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
        // 实际项目中，这里应该处理上传后的图片信息
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };
  
  // 定义steps配置
  const tourSteps = [
    {
      key: 'style',
      title: '选择背景风格',
      description: '根据您的需求选择合适的背景风格，如自然风景、抽象艺术等',
    },
    {
      key: 'color',
      title: '设置主色调',
      description: '输入您想要的主色调，如蓝色、红色、绿色等',
    },
    {
      key: 'description',
      title: '添加描述词（可选）',
      description: '输入更详细的描述，帮助AI更好地理解您的需求',
    },
    {
      key: 'upload',
      title: '上传参考图（可选）',
      description: '您可以上传一张参考图片，让AI参考其风格生成新的背景',
    },
    {
      key: 'submit',
      title: '生成背景图片',
      description: '完成所有配置后，点击此按钮开始生成背景图片',
    },
    {
      key: 'result',
      title: '查看生成结果',
      description: '生成成功后，您可以在此处查看、下载或重新生成背景图片',
    },
  ];

  // 组织ref引用
  const tourRefs = {
    style: styleRef,
    color: colorRef,
    description: descriptionRef,
    upload: uploadRef,
    submit: submitRef,
    result: resultRef,
  };
  
  return (
    <>
      <div style={{ padding: 24 }}>
        <div style={{ marginBottom: 24 }}>
          <h1 style={{ fontSize: 28, fontWeight: 'bold', marginBottom: 8, display: 'flex', alignItems: 'center' }}>
            <SettingOutlined style={{ marginRight: 8 }} /> 一键背景生成
            <TourGuideButton onClick={showTour}  />
          </h1>
          <p style={{ color: '#666' }}>通过简单的配置，快速生成精美的背景图片</p>
        </div>
        
        <Row gutter={[24, 24]}>
          <Col xs={24} md={12}>
            <Card title="生成配置" style={{ height: '100%' }}>
              <Form layout="vertical" onFinish={handleSubmit}>
                <Form.Item
                  name="style"
                  label="背景风格"
                  rules={[{ required: true, message: '请选择背景风格' }]}
                >
                  <div ref={styleRef}>
                    <Select placeholder="请选择背景风格">
                      <Option value="natural">自然风景</Option>
                      <Option value="abstract">抽象艺术</Option>
                      <Option value="tech">科技感</Option>
                      <Option value="minimal">极简风格</Option>
                      <Option value="vintage">复古风格</Option>
                    </Select>
                  </div>
                </Form.Item>
                
                <Form.Item
                  name="color"
                  label="主色调"
                  rules={[{ required: true, message: '请输入主色调' }]}
                >
                  <div ref={colorRef}>
                    <Input placeholder="例如：蓝色、红色、绿色等" />
                  </div>
                </Form.Item>
                
                <Form.Item
                  name="description"
                  label="描述词"
                >
                  <div ref={descriptionRef}>
                    <Input.TextArea 
                      rows={4} 
                      placeholder="输入更详细的描述，帮助AI更好地理解您的需求" 
                    />
                  </div>
                </Form.Item>
                
                <Form.Item
                  label="上传参考图（可选）"
                >
                  <Upload {...uploadProps}>
                    <div ref={uploadRef}>
                      <Button icon={<UploadOutlined />}>点击上传</Button>
                    </div>
                  </Upload>
                </Form.Item>
                
                <Form.Item>
                  <div ref={submitRef}>
                    <Button 
                      type="primary" 
                      htmlType="submit" 
                      loading={loading} 
                      block 
                    >
                      生成背景图片
                    </Button>
                  </div>
                </Form.Item>
              </Form>
            </Card>
          </Col>
          
          <Col xs={24} md={12}>
            <Card title="生成结果" style={{ height: '100%' }}>
              <div 
                style={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center', 
                  height: '400px', 
                  backgroundColor: '#f0f2f5',
                  borderRadius: 8,
                  overflow: 'hidden'
                }} 
                ref={resultRef}
              >
                {loading ? (
                  <div style={{ textAlign: 'center' }}>
                    <p>正在生成背景图片，请稍候...</p>
                  </div>
                ) : imageUrl ? (
                  <img 
                    src={imageUrl} 
                    alt="生成的背景图片" 
                    style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
                  />
                ) : (
                  <div style={{ textAlign: 'center', color: '#999' }}>
                    <p>配置完成后，点击"生成背景图片"按钮获取结果</p>
                  </div>
                )}
              </div>
              
              {imageUrl && (
                <div style={{ marginTop: 16, textAlign: 'center' }}>
                  <Button style={{ marginRight: 8 }}>下载图片</Button>
                  <Button type="primary">重新生成</Button>
                </div>
              )}
            </Card>
          </Col>
        </Row>
      </div>
      
      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </>
  );
};

export default OneKeyBackground;